package com.example.xxtautosignjava.service.impl;

import com.example.xxtautosignjava.entity.Course;
import com.example.xxtautosignjava.entity.CourseAndActiveId;
import com.example.xxtautosignjava.entity.CourseStatus;
import com.example.xxtautosignjava.entity.vo.CourseVo;
import com.example.xxtautosignjava.entity.vo.GetSignInVo;
import com.example.xxtautosignjava.entity.vo.SignInfoVo;
import com.example.xxtautosignjava.handler.XxtHandler;
import com.example.xxtautosignjava.service.LoginService;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
//@Scope("prototype")
public class LoginServiceImpl implements LoginService {
    List<CourseAndActiveId> courseAndActiveIds=new CopyOnWriteArrayList<>();
    ArrayList<Course> courses = new ArrayList<>();
    String content = null;




    @Override
    public ArrayList<Course> getCouse(String phone, String pwd) throws IOException, URISyntaxException {
        BasicCookieStore store = login(phone, pwd);

        if (store.getCookies().isEmpty()){
            throw new XxtHandler(2001,"cookie失效");
        }
        //获取响应
        Connection.Response response = Jsoup.connect("https://mooc1-2.chaoxing.com/visit/courselistdata?courseType=1&courseFolderId=0&courseFolderSize=0").cookies(convertCookieStore(store)).method(Connection.Method.GET).execute();
        URL url = response.url();
         courses = new ArrayList<>();
        if (response.statusCode() == 200) {
            //通过这种方式可以获得响应的HTML文件
            String html = new String(response.bodyAsBytes(), "utf8");
            //获取html内容，但对应的是Document类型
            Document document = response.parse();
            //这里html和document数据是一样的，但document是经过格式化的
            System.out.println(document);

            for (Element node : document.select("li")) {
                Course course = new Course();
//                System.out.println(node.getElementsByClass("course clearfix"));
//                System.out.println(node.getElementsByClass("course-info"));
//                System.out.println(node.getElementsByClass("course clearfix").attr("courseid"));
//
//                System.out.println(node.getElementsByClass("course clearfix").attr("clazzid"));
//                System.out.println(node.getElementsByClass("course-name overHidden2").attr("title"));
//                System.out.println("--------------------");


                String flag = node.getElementsByClass("course clearfix").attr("courseid");
                if (flag != "") {
                    course.setCourse_id(node.getElementsByClass("course clearfix").attr("courseid"));

                    course.setClass_id(node.getElementsByClass("course clearfix").attr("clazzid"));

                    course.setClass_name(node.getElementsByClass("course-name overHidden2").attr("title"));
                    course.setClass_img(node.select("a").select("img").attr("src"));
                    course.setClass_href(node.select("a").attr("href"));
                    course.setClass_teacher( node.select("[class=line2]").attr("title"));
                    course.setClass_room(node.getElementsByClass("overHidden1").text());

                    courses.add(course);


                }
            }


        }
        System.out.println(courses);
        return courses;
    }






    public List<CourseAndActiveId> getActiveId(String phone, String pwd) throws URISyntaxException, IOException {

        ArrayList<Course> list = getCouse(phone,pwd );
        courseAndActiveIds.clear();
        ExecutorService executor = Executors.newFixedThreadPool(100);
        for (Course course : list) {
            executor.submit(()->{
//                newCollList.add(integer+1);

                try {
                    getActiveId(course,phone,pwd);

                } catch (URISyntaxException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        executor.shutdown();
        try {
            executor.awaitTermination(6, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return courseAndActiveIds;
    }



     void getActiveId(Course course,String phone,String pwd) throws URISyntaxException, IOException {
         BasicCookieStore store = login(phone, pwd);


         CloseableHttpClient httpclient = HttpClients.custom()
                 .setDefaultCookieStore(store)//设置Cookie
                 .build();
        CourseAndActiveId courseAndActiveId =new CourseAndActiveId();
                    courseAndActiveId.setCourse_id(course.getCourse_id());
                    courseAndActiveId.setClass_id(course.getClass_id());
                    courseAndActiveId.setClass_name(course.getClass_name());
                     courseAndActiveId.setClass_room(course.getClass_room());
                     courseAndActiveId.setClass_teacher(course.getClass_teacher());
                    URI uri = new URIBuilder("https://mobilelearn.chaoxing.com/widget/pcpick/stu/index")
//                    .setParameter("courseId",courses.get(i).getCourse_id())
//                    .setParameter("jclassId",courses.get(i).getClass_id())
                            .setParameter("courseId", course.getCourse_id())
                            .setParameter("jclassId", course.getClass_id())
                            .build();
                    HttpGet httpGet = new HttpGet(uri);
                    CloseableHttpResponse response = httpclient.execute(httpGet);

                    if (response.getStatusLine().getStatusCode() == 200) {
                        String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                        Document doc = Jsoup.parse(content);
//            doc.getElementsByClass("Mct");

                        Elements startList = doc.select("#startList");
                        for (Element node : startList.select(".Mct")) {
//                            System.out.println(node);
                            node.getElementsByClass("Mct").attr("onclick");
                            String activeId = node.getElementsByClass("Mct").attr("onclick").substring(13, 26);
                            System.out.println(activeId);
                            courseAndActiveId.setActive_id(activeId);
                            if (activeId!=null){
                                courseAndActiveId.setActive_id(activeId);
                                courseAndActiveIds.add(courseAndActiveId);
                            }
                        }

                        System.out.println(courseAndActiveIds);
                    }
    }

    public HashMap<String, String> convertCookie(String cookie) {
        HashMap<String, String> cookiesMap = new HashMap<String, String>();
        String[] items = cookie.trim().split(";");
        for (String item : items) cookiesMap.put(item.split("=")[0], item.split("=")[1]);
        return cookiesMap;
    }

    public HashMap<String, String> convertCookieStore(BasicCookieStore store) {
        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < store.getCookies().size(); i++) {
            map.put(store.getCookies().get(i).getName(), store.getCookies().get(i).getValue());
        }
        System.out.println(map);
        return map;
    }
    public BasicCookieStore login(String phone, String pwd) throws IOException, URISyntaxException {
        BasicCookieStore store = new BasicCookieStore();

        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(store).build();

        URI uri = new URIBuilder("https://passport2.chaoxing.com/api/login")
                .setParameter("name", phone)
                .setParameter("pwd", pwd).build();
        HttpGet httpGet = new HttpGet(String.valueOf(uri));

        // 发送请求,获取响应结果
        CloseableHttpResponse response = null;

        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("content"+content);
                System.out.println("获取到store"+store);

            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        return store;
    }

    @Override
    public String getLogin(String phone, String pwd) throws URISyntaxException, IOException {
        BasicCookieStore store = new BasicCookieStore();

        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(store).build();

        URI uri = new URIBuilder("https://passport2.chaoxing.com/api/login")
                .setParameter("name", phone)
                .setParameter("pwd", pwd).build();
        HttpGet httpGet = new HttpGet(String.valueOf(uri));

        // 发送请求,获取响应结果
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应数据
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("content"+content);
                System.out.println("store"+store.toString());
                //读取cookie信息

                List<Cookie> cookielist = store.getCookies();

                for (Cookie cookie : cookielist) {
                    String name = cookie.getName();
                    String value = cookie.getValue();
                    System.out.print(name+"  :  ");
                    System.out.print(value);
                    System.out.println();
                }
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        return content;
    }

    @Override
    public List<CourseStatus> getCourseStatus(String phone, String pwd, CourseVo course) throws IOException, URISyntaxException {
        BasicCookieStore store = login(phone, pwd);

        List<CourseStatus> courseStatusList =new ArrayList<>();

        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCookieStore(store)//设置Cookie
                .build();
        CourseAndActiveId courseAndActiveId =new CourseAndActiveId();
        courseAndActiveId.setCourse_id(course.getCourse_id());
        courseAndActiveId.setClass_id(course.getClass_id());

        URI uri = new URIBuilder("https://mobilelearn.chaoxing.com/widget/pcpick/stu/index")
//                    .setParameter("courseId",courses.get(i).getCourse_id())
//                    .setParameter("jclassId",courses.get(i).getClass_id())
                .setParameter("courseId", course.getCourse_id())
                .setParameter("jclassId", course.getClass_id())
                .build();
        HttpGet httpGet = new HttpGet(uri);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            Document doc = Jsoup.parse(content);
//            System.out.println(doc);

            Elements startList = doc.select("#startList");
//            System.out.println(endList);
            for (Element node : startList.select("[class=Mct]")) {
                String activeId= node.getElementsByClass("Mct").attr("onclick").substring(13,26);


                String a = node.getElementsByTag("a").get(1).text();
                System.out.println(a);
                CourseStatus courseStatus =new CourseStatus();

               courseStatus.setStatus("正在签到");
               courseStatus.setType(a);
               courseStatus.setActiveid(activeId);
                courseStatusList.add(courseStatus);
            }

            Elements endList = doc.select("#endList");
//            System.out.println(endList);
            for (Element node : endList.select("[class=Mct]")) {
                String activeId= node.getElementsByClass("Mct").attr("onclick").substring(13,26);
                System.out.println(activeId);
                String a = node.getElementsByTag("a").get(1).text();
                System.out.println(a);
                CourseStatus courseStatus =new CourseStatus();
                courseStatus.setStatus("过期的签到");
                courseStatus.setType(a);
                courseStatus.setActiveid(activeId);
                courseStatusList.add(courseStatus);
            }




        }


        return courseStatusList;
    }

    @Override
    public SignInfoVo getSignInfo(String phone, String pwd , GetSignInVo getSignInVo) throws IOException, URISyntaxException {
        BasicCookieStore store = login(phone, pwd);

        SignInfoVo signInfoVo = new SignInfoVo();


        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCookieStore(store)//设置Cookie
                .build();

        URI uri = new URIBuilder("https://mobilelearn.chaoxing.com/widget/sign/pcStuSignController/preSign")
//                    .setParameter("courseId",courses.get(i).getCourse_id())
//                    .setParameter("jclassId",courses.get(i).getClass_id())
//        activeId=8000047975716&classId=59847534&fid=851&courseId=227018487
                .setParameter("activeId",getSignInVo.getActiveid())
                .setParameter("classId",getSignInVo.getClassId())
                .setParameter("fid",getSignInVo.getFid())
                .setParameter("courseId",getSignInVo.getCourseId())
                .build();
        HttpGet httpGet = new HttpGet(uri);
        CloseableHttpResponse response = httpclient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            Document doc = Jsoup.parse(content);
            System.out.println(doc);

            Elements startList = doc.select("[class=qd_Success padtop120]");
            String span = startList.get(0).getElementsByTag("span").text();
            System.out.println(span);
            signInfoVo.setResult(span);
            String time=startList.get(0).getElementsByTag("em").text();
            System.out.println(time);
            signInfoVo.setTime(time);
//            System.out.println(endList);
//            for (Element node : startList.select("[class=Mct]")) {
//                String activeId= node.getElementsByClass("Mct").attr("onclick").substring(13,26);
//
//            }



        }


        return signInfoVo;
    }
}
